<template>
  <a-modal v-model:visible="config.visible" :title="config.title" :size="appStore.table.size" width="80%"
    class="custom-modal" @cancel="handleCancel" @before-ok="handleBeforeOk">
    <a-form ref="formRef" :label-col="labelCol" :wrapper-col="wrapperCol" :model="form" :rules="rules">
      <a-form-item label="文章类别" field="indexCategoryId">
        <a-select v-model="form.indexCategoryId" placeholder="文章类型">
          <a-option v-for="(i, x) in data.typelist" :key="x" :value="i.id" :label="i.name" />
        </a-select>
      </a-form-item>
      <a-form-item label="文章标题" field="title">
        <a-input v-model="form.title" />
      </a-form-item>
      <a-form-item label="文章摘要" field="summary">
        <a-input v-model="form.summary" />
      </a-form-item>

      <a-form-item label="文章来源" field="source">
        <a-input v-model="form.source" />
      </a-form-item>

      <a-form-item label="文章封面" field="cover">
        <image-upload v-model="form.cover" />
      </a-form-item>

      <!-- <a-form-item label="文章描述"   field="description">
        <a-input v-model="form.description" />
      </a-form-item> -->

      <a-form-item label="文章详情" field="content">
        <section style="height: 250px">
          <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :default-config="toolbarConfig"
            :mode="mode" />
          <Editor v-model="form.content" style="overflow-y: hidden" :default-config="editorConfig" :mode="mode"
            @on-created="handleCreated" />
        </section>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import ImageUpload from '@/components/ImageUpload.vue';
import '@wangeditor/editor/dist/css/style.css';
// import MarkdownEditor from 'markdown-editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

const emit = defineEmits(['ok']);
const editorRef = shallowRef();
const mode = ref('default');
const content = ref('<p>文章内容</p>');
const labelCol = { style: { width: '100px' } };
const wrapperCol = { span: 14 };
const appStore = useAppStore();
const formRef = ref();
const config = reactive({
  visible: false,
  isCreate: false,
  title: '',
});

const form = ref({
  id: undefined,
  indexCategoryId: undefined,
  title: undefined,
  summary: undefined,
  source: undefined,
  cover: undefined,
  // description: undefined,
  content: undefined,
  contentType: 'html',
});

const data = reactive({
  typelist: [] as any,
});

const rules = {
  indexCategoryId: [{ required: true, message: '请选择文章类别' }],
  title: [{ required: true, message: '请输入文章标题' }],
};

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

const toolbarConfig = {};
const editorConfig = { placeholder: '请输入内容...' };

// 组件销毁时，也及时销毁编辑器
onUnmounted(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const show = async () => {
  formRef.value.resetFields();
  config.isCreate = true;
  config.title = '新增';
  form.value.id = undefined;
  try {
    await loadRoles();
  } catch (e: any) {
    useHandleError(e);
  }

  config.visible = true;
};

const showEdit = async (obj: any) => {
  formRef.value.resetFields();
  config.isCreate = false;
  config.title = '编辑';
  form.value = JSON.parse(obj);
  try {
    await loadRoles();
  } catch (e: any) {
    useHandleError(e);
  }

  config.visible = true;
};

const deleteAt = async (id: any) => {
  try {
    // eslint-disable-next-line no-shadow
    const data = { id };
    await axios.postForm<any>(
      `/api/admin/index-article/delete`,
      jsonToFormData(data)
    );
    useNotificationSuccess('操作成功');
    emit('ok');
  } catch (e: any) {
    useHandleError(e);
  }
};

const loadRoles = async () => {
  const res: any = await axios.get('/api/admin/index-category/list', {
    params: { page: 1, limit: 200 },
  });
  data.typelist = res.results;
};

const handleCancel = () => {
  formRef.value.resetFields();
};
const handleBeforeOk = async (done: (closed: boolean) => void) => {
  const validateErr = await formRef.value.validate();
  if (validateErr) {
    done(false);
    return;
  }
  try {
    const url = config.isCreate
      ? '/api/admin/index-article/create'
      : '/api/admin/index-article/update';
    await axios.postForm<any>(url, jsonToFormData(form.value));
    useNotificationSuccess('提交成功');
    emit('ok');
    done(true);
  } catch (e: any) {
    useHandleError(e);
    done(false);
  }
};

defineExpose({
  show,
  showEdit,
  deleteAt,
});
</script>

<style lang="less" scoped>
@import url('@wangeditor/editor/dist/css/style.css');

.editor-container {
  max-width: 600px;
  margin: 0 auto;
  border: ipx solid #d9d9d9;
  border-radius: 2px;
}

.editor-toolbar {
  border-bottom: 1px solid #d9d9d9;
}

.editor-content {
  min-height: 300px;
}

.custom-modal {
  height: 350px;
}
</style>
